package com.rcl.mvvmdemo

import android.text.TextUtils
import android.util.Log
import com.rcl.mvvmdemo.lifecycle.AbsLifecycle
import com.rcl.mvvmdemo.lifecycle.ILifecycle
import com.rcl.mvvmdemo.lifecycle.ILifecycleOwner
import com.rcl.mvvmdemo.lifecycle.LifecycleState

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2020/11/4.
 * PS: Not easy to write code, please indicate.
 */
class LoginPresenter(owner: ILifecycleOwner) : AbsLifecycle() {

    init {
        owner.getLifecycleProvider().addLifecycleListener(this)
    }

    private val userModel by lazy {
        UserModel()
    }

    fun checkUserNameState(account: String, callback: OnCheckUserNameStateResultCallback) {
        userModel.checkUserStatus(account) {
            when (it) {
                0 -> {
                    callback.onExist()
                }

                1 -> {
                    callback.onNotExist()
                }
            }
        }
    }

    interface OnCheckUserNameStateResultCallback {
        fun onNotExist()
        fun onExist()
    }

    fun doLogin(userName: String, password: String, callback: OnDoLoginStatusChange) {

        //检查账号格式是否正确
        if (TextUtils.isEmpty(userName)) {
            callback.onAccountFormatError()
            return
        }
        //检查密码格式是否正确
        if (TextUtils.isEmpty(password)) {
            callback.onPasswordEmpty()
            return
        }

        userModel.doLogin(userName, password) {
            when (it) {
                UserModel.STATE_LOGIN_LOADING -> {
                    callback.onLogin()
                }

                UserModel.STATE_LOGIN_SUCCESS -> {
                    callback.onLoginSuccess()
                }

                UserModel.STATE_LOGIN_FAILED -> {
                    callback.onLoginFailed()
                }
            }
        }
    }

    interface OnDoLoginStatusChange {
        fun onAccountFormatError()
        fun onPasswordEmpty()
        fun onLogin()
        fun onLoginSuccess()
        fun onLoginFailed()
    }

    override fun onViewLifeStateChange(state: LifecycleState) {
        Log.i("aaaaa", "LoginPresenter current state: $state")
    }
}